package com.rykj.qxj.server.services.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rykj.qxj.server.dao.ApplyManageMapper;
import com.rykj.qxj.server.model.entity.Apply;
import com.rykj.qxj.server.model.entity.ApplyApi;
import com.rykj.qxj.server.model.entity.ApplyRelateParty;
import com.rykj.qxj.server.model.param.ApplyManagerParams;
import com.rykj.qxj.server.services.IApplyManageService;
import com.rykj.qxj.server.util.Pager;
import com.rykj.qxj.server.util.ShortUUID;
import com.techindata.cacheredis.CacheZSet;
import lombok.extern.log4j.Log4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

@Log4j
@Service("applyManageService")
public class ApplyManageServiceImpl implements IApplyManageService {
    @Resource
    private ApplyManageMapper applyManageMapper;
    private static final String PER_APPLICATION_VISITCOUNT= "perApplicationVisitCount";
    @Override
    public  void saveApply(ApplyManagerParams applyManagerParams) throws Exception{
        try {
            Apply apply = applyManagerParams.getApply();
            apply.setApplyId(ShortUUID.generateShortUuid());
            apply.setApplyKey(DigestUtils.md5Hex(UUID.randomUUID()+apply.getApplyId()));
            applyManageMapper.saveApply(apply);
            int  id = apply.getId();
            List<ApplyRelateParty> relateParties = applyManagerParams.getRelateParties();
            for (ApplyRelateParty relateParty: relateParties) {
                relateParty.setApplyId(id);
                relateParty.setCreatedBy(applyManagerParams.getApply().getCreatedBy());
            }
            applyManageMapper.saveApplyRelateParty(relateParties);
            List<Integer> accountIds=applyManagerParams.getAccountIds();
            if(!CollectionUtils.isEmpty(accountIds)){
                List<Map<String,Object>> applyAccounts = new ArrayList<>();
                accountIds.forEach(accountId->{
                    Map<String,Object> accountMAp= new HashMap<>();
                    accountMAp.put("applyId",id);
                    accountMAp.put("accountId",accountId);
                    accountMAp.put("createdBy",applyManagerParams.getApply().getCreatedBy());
                    applyAccounts.add(accountMAp);
                });
                applyManageMapper.saveApplyAccount(applyAccounts);
            }
            List<Integer> categoryIds=applyManagerParams.getCategoryIds();
            if(!CollectionUtils.isEmpty(categoryIds)){
                List<Map<String,Object>> categorys = new ArrayList<>();
                categoryIds.forEach(categoryId->{
                    Map<String,Object> categoryMAp= new HashMap<>();
                    categoryMAp.put("applyId",id);
                    categoryMAp.put("categoryId",categoryId);
                    categorys.add(categoryMAp);
                });
                applyManageMapper.saveApplyCategorys(categorys);
            }
        }catch (Exception e){
            log.error("添加应用信息失败", e);
            throw  new Exception("添加应用信息失败");
        }

    }

    @Override
    public void updateApply(Apply apply)throws  Exception {
        try {
            List<Integer> accountIds=apply.getAccountIds();
            if(com.rykj.qxj.server.common.utils.CollectionUtils.isNotEmpty(accountIds)){
                List<Map<String,Object>> accounts = new ArrayList<>();
                for (Integer aid:accountIds ) {
                    Map<String,Object>  account = new HashMap<>();
                    account.put("accountId",aid);
                    account.put("applyId",apply.getId());
                    account.put("createdBy",apply.getCreatedBy());
                    accounts.add(account);
                    applyManageMapper.deleteApplyAccount(account);
                }
                applyManageMapper.saveApplyAccount(accounts);
            }
            applyManageMapper.updateApply(apply);
        }catch (Exception e){
            log.error("修改应用信息失败", e);
            throw  new Exception("修改应用信息失败");
        }

    }

    @Override
    public void updateApplyRelateParty(List<ApplyRelateParty> relateParties) throws  Exception{
        for (ApplyRelateParty relateParty:relateParties) {
            applyManageMapper.updateApplyRelateParty(relateParty);
        }

    }

    @Override
    public void deleteApplyById(Integer applyId) throws  Exception{
        applyManageMapper.deleteApply(applyId);
    }

    @Override
    public Pager getApplys(Integer pageNum, Integer pageSize, String applyName, Integer categoryId, String issuance, Integer userId, String sysType) {
        int thisPage = (pageNum - 1) * pageSize;
        Pager pager = new Pager(pageNum, pageSize);
        Map<String,Object> paraMap =new HashMap<>();
        if("%".equals(applyName)){
            applyName ="\\%";
        }
        paraMap.put("categoryId",categoryId);
        paraMap.put("applyName",applyName);
        paraMap.put("issuance",issuance);
        paraMap.put("userId",userId);
        paraMap.put("thisPage",thisPage);
        paraMap.put("pageSize",pageSize);
        List<Map<String,Object>> applies= applyManageMapper.getApplys(paraMap);
        if(!CollectionUtils.isEmpty(applies) && "door".equals(sysType)){
            applies.forEach(a->{
                a.put("applyId",null);
                a.put("applyKey",null);
            });
        }
        pager.setTotalCount(applyManageMapper.getApplysCount(paraMap));
        pager.setItems(applies);
        return  pager;
    }

    @Override
    public List<ApplyRelateParty> getApplyRelateParties(Integer applyId) {
        return applyManageMapper.getApplyRelateParties(applyId);
    }

  /*  public JSONArray getApplyAccounts(Integer applyId,String token) throws IOException {
        String butlerUrl="http://192.168.0.78:8002/butler/manage/user/getUsersByIds";
        List<Integer> accountIds=  applyManageMapper.getAccountIds(applyId);
        JSONArray jsonArray = new JSONArray();
        if (!CollectionUtils.isEmpty(accountIds)){
            String retUsers =  HttpClientUtils.doTokenPost(butlerUrl,token, JSONUtils.toJSONString(accountIds));
            JSONObject object = JSONObject.parseObject(retUsers);
            log.info("====查询账户信息===="+object);
           *//*   String code = object.getString("code");
              String message = object.getString("message");*//*
            jsonArray = object.getJSONArray("data");
        }
        return jsonArray;
    }*/

    @Override
    public List<Map<String,Object>> getAppApiVisitCount(String applyId, String[] apiIds, String dataType) {
        return applyManageMapper.getAppApiVisitCount(applyId,apiIds,dataType);
    }

    @Override
    public Apply getApplyDetails(Integer applyId) {
        Map<String,Object> paraMap = new HashMap<>();
        paraMap.put("applyId",applyId);
        List<Integer> accountIds=  applyManageMapper.getAccountIds(applyId);
        Apply apply =applyManageMapper.getApplyDetails(paraMap);
        apply.setAccountIds(accountIds);
        return apply;
    }

    @Override
    public PageInfo getApplyAPIs(Integer pageNum, Integer pageSize, String apiName, Integer applyId) {
        PageHelper.startPage(pageNum,pageSize);
        Map<String,Object> paraMap =new HashMap<>();
        if("%".equals(apiName)){
            apiName ="\\%";
        }
        paraMap.put("apiName",apiName);
        paraMap.put("applyId",applyId);
        List<Map<String,Object>> appApis= applyManageMapper.getApplyAPIs(paraMap);
        PageInfo pageInfo = new PageInfo(appApis);
        return  pageInfo;
    }

    @Override
    public PageInfo getApplyInfo(Integer pageNum, Integer pageSize, String applyName) {
        PageHelper.startPage(pageNum,pageSize);
        Map<String,Object> paraMap =new HashMap<>();
        if("%".equals(applyName)){
            applyName ="\\%";
        }
        paraMap.put("applyName",applyName);
        List<Map<String,Object>> appApis= applyManageMapper.getApplyInfo(paraMap);
        for(Map<String,Object> map : appApis){
            double zscore = CacheZSet.zscore(PER_APPLICATION_VISITCOUNT, (String) map.get("applyKey"));
            if(zscore==-1.0) {
                map.put("applyVisitCount", 0);
            }else {
                map.put("applyVisitCount", zscore);
            }
            map.remove("applyKey");

        }
        PageInfo pageInfo = new PageInfo(appApis);
        return  pageInfo;
    }

    @Override
    public PageInfo getApplyUnboundAPIs(Integer pageNum, Integer pageSize, String apiName, Integer applyId) {
        PageHelper.startPage(pageNum,pageSize);
        Map<String,Object> paraMap =new HashMap<>();
        if("%".equals(apiName)){
            apiName ="\\%";
        }
        paraMap.put("apiName",apiName);
        paraMap.put("applyId",applyId);
        List<Map<String,Object>> appApis=null;
        //if(apiType.equals("subject")) {
        	appApis= applyManageMapper.getApplyUnboundAPIs(paraMap);
        //}
       // if(apiType.equals("isoutside")) {
        //	appApis= applyManageMapper.getApplyUnboundAndOutSideAPIs(paraMap);
        //}
        PageInfo pageInfo = new PageInfo(appApis);
        return  pageInfo;
    }

    @Override
    public void saveApplyApi(List<ApplyApi> applyApis) throws  Exception{
        List<ApplyApi> apis = new ArrayList<>();
        if(!CollectionUtils.isEmpty(applyApis)){
            Map<String,Object> paraMap = new HashMap<>();
            for (ApplyApi applyApi: applyApis) {
                paraMap.put("apiId",applyApi.getApiId());
                paraMap.put("applyId",applyApi.getApplyId());
                if(applyManageMapper.getApiAppCount(paraMap)==0){
                    apis.add(applyApi);
                }
            }
        }
        if(!CollectionUtils.isEmpty(apis)){
            applyManageMapper.saveApplyApi(apis);
        }
    }
    @Override
    public void deleteApplyApiById(Integer id) throws  Exception{
        applyManageMapper.deleteApplyApiById(id);
    }

    @Override
    public void updateApplyIssuance(String issuance, Integer applyId) {
        Map<String,Object> paraMap =new HashMap<>();
        paraMap.put("issuance",issuance);
        paraMap.put("applyId",applyId);
        applyManageMapper.updateApplyIssuance(paraMap);
    }

    @Override
    public Apply selectApplyByAppKey(String appKey) {
    	return applyManageMapper.selectApplyByAppKey(appKey);

    }

    @Override
    public Apply checkApplyRep(String applyName, String applyEng) {
        Map<String,Object> paraMap =new HashMap<>();
        paraMap.put("applyName",applyName);
        paraMap.put("applyEng",applyEng);
       return applyManageMapper.checkApplyRep(paraMap);
    }

    @Override
    public List<Apply> findAllApplys() {
        return applyManageMapper.findAllApplys(new HashMap<>());
    }

	@Override
	public Map<String, Object> applicationTotal() {
		return applyManageMapper.applicationTotal();
	}

	@Override
	public List<Apply> findApplysListByIssuance() {
		return applyManageMapper.findApplysListByIssuance();
	}

	@Override
	public Apply selectApplyByAppKeyIsExist(String applyKey) {
		return applyManageMapper.selectApplyByAppKeyIsExist(applyKey);
	}
    @Override
    public Integer getApplysCount(String applyName, Integer categoryId, String issuance, Integer userId) {
        Map<String,Object> paraMap =new HashMap<>();
        if("%".equals(applyName)){
            applyName ="\\%";
        }
        paraMap.put("categoryId",categoryId);
        paraMap.put("applyName",applyName);
        paraMap.put("issuance",issuance);
        paraMap.put("userId",userId);
        return applyManageMapper.getApplysCount(paraMap);
    }

	@Override
	public List<ApplyApi> selectCurrentApplyListByAppId(int applyId) {
		return applyManageMapper.selectCurrentApplyListByAppId(applyId);
	}

	@Override
	public Integer selectApiCountByApplyId(Integer applyId) {
		return applyManageMapper.selectApiCountByApplyId(applyId);
	}

	@Override
	public Integer selectNewAddApplyNear7day() {
		return applyManageMapper.selectNewAddApplyNear7day();
	}

	@Override
	public Integer selectCountApply() {
		return applyManageMapper.selectCountApply();
	}

	@Override
	public Integer selectCountOnlineApply() {
		return applyManageMapper.selectCountOnlineApply();
	}

	@Override
	public Integer selectCountNotOnlineApply() {
		return applyManageMapper.selectCountNotOnlineApply();
	}

    @Override
    public Integer getAppTotal() {

        return applyManageMapper.getAppTotal();
    }
}
